//
//  LBFileModule.m
//  LBReact
//
//  Created by WuShiHai on 19/5/24.
//  Copyright (c) 2019 Lebbay. All rights reserved.
//

#import "LBFileModule.h"
#import <LBFoundation/LBFoundation.h>

@implementation LBFileModule

RCT_EXPORT_MODULE(fileUtil)

+ (BOOL)requiresMainQueueSetup {
    return NO;
}

- (NSDictionary *)constantsToExport {
    return @{
             @"CacheDir": [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject],
             @"DocumentDir": [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject],
             @"MainBundleDir": [[NSBundle mainBundle] bundlePath],
             @"MovieDir": [NSSearchPathForDirectoriesInDomains(NSMoviesDirectory, NSUserDomainMask, YES) firstObject],
             @"MusicDir": [NSSearchPathForDirectoriesInDomains(NSMusicDirectory, NSUserDomainMask, YES) firstObject],
             @"PictureDir": [NSSearchPathForDirectoriesInDomains(NSPicturesDirectory, NSUserDomainMask, YES) firstObject],
             };
}

RCT_EXPORT_METHOD(isExist:(NSString *)path
                  callback:(RCTResponseSenderBlock)callback) {
    LBBlockSafeRun(callback, @[@([self isExistFrom:path])]);
}

RCT_EXPORT_METHOD(readFile:(NSString *)path callback:(RCTResponseSenderBlock)callback) {
    if (path && path.length > 0) {
        BOOL isExist = [self isExistFrom:path];
        if (!isExist) {
            LBBlockSafeRun(callback, @[]);
        } else {
            NSError *error = nil;
            NSString *content = [NSString stringWithContentsOfFile:path
                                                          encoding:NSUTF8StringEncoding
                                                             error:&error];
            if (error || content == nil) {
                LBBlockSafeRun(callback, @[content]);
            } else {
                LBBlockSafeRun(callback, @[]);
            }
        }
    } else {
        LBBlockSafeRun(callback, @[]);
    }
}

RCT_EXPORT_METHOD(writeFile:(NSString *)path
                  content:(NSString *)content
                  callback:(RCTResponseSenderBlock)callback) {
    if (path && path.length > 0 && [self createFolder:path] && content.length > 0) {
        NSData *data = [content dataUsingEncoding:NSUTF8StringEncoding];
        LBBlockSafeRun(callback, @[@([self saveLocal:data
                                                path:path])]);
    } else {
        LBBlockSafeRun(callback, @[@(NO)]);
    }
}

- (BOOL)isExistFrom:(NSString *)path {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isDir = NO;
    BOOL existed = [fileManager fileExistsAtPath:path isDirectory:&isDir];
    return existed && !isDir;
}

- (BOOL)createFolder:(NSString *)path {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *folder = [path stringByDeletingLastPathComponent];
    BOOL isDir = NO;
    BOOL existed = [fileManager fileExistsAtPath:folder isDirectory:&isDir];
    if (!isDir && existed) {
        return NO;
    }
    
    if (!(isDir == YES && existed == YES)) {
        return [fileManager createDirectoryAtPath:folder
                      withIntermediateDirectories:YES
                                       attributes:nil
                                            error:nil];
    }
    
    return YES;
}

- (BOOL)saveLocal:(NSData *)data
             path:(NSString *)path {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *folder = [path stringByDeletingLastPathComponent];
    BOOL isDir = NO;
    BOOL existed = [fileManager fileExistsAtPath:folder isDirectory:&isDir];
    if (!isDir && existed) {
        return NO;
    }
    
    if (!(isDir == YES && existed == YES)) {
        if (![fileManager createDirectoryAtPath:folder
                    withIntermediateDirectories:YES
                                     attributes:nil
                                          error:nil]) {
            return NO;
        };
    }
    
    return [data writeToFile:path
                     options:(NSDataWritingOptions)0
                       error:nil];
}

@end
